package com.wujie.mall.infrastructure.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ 配置类
 * 定义交换机、队列、绑定关系等
 * 
 * @author wujie
 * @since 2024-08-26
 */
@Configuration
public class RabbitMQConfig {

    // ===============================
    // = 交换机定义
    // ===============================
    
    /**
     * 订单相关的主题交换机
     */
    public static final String ORDER_TOPIC_EXCHANGE = "mall.order.topic";
    
    /**
     * 支付相关的主题交换机
     */
    public static final String PAYMENT_TOPIC_EXCHANGE = "mall.payment.topic";
    
    /**
     * 营销相关的主题交换机
     */
    public static final String MARKETING_TOPIC_EXCHANGE = "mall.marketing.topic";

    // ===============================
    // = 队列定义
    // ===============================
    
    /**
     * 订单创建队列
     */
    public static final String ORDER_CREATED_QUEUE = "mall.order.created";
    
    /**
     * 订单支付队列
     */
    public static final String ORDER_PAYMENT_QUEUE = "mall.order.payment";
    
    /**
     * 库存扣减队列
     */
    public static final String INVENTORY_DEDUCTION_QUEUE = "mall.inventory.deduction";
    
    /**
     * 通知队列
     */
    public static final String NOTIFICATION_QUEUE = "mall.notification";

    // ===============================
    // = 路由键定义
    // ===============================
    
    public static final String ORDER_CREATED_ROUTING_KEY = "order.created";
    public static final String ORDER_PAID_ROUTING_KEY = "order.paid";
    public static final String INVENTORY_DEDUCT_ROUTING_KEY = "inventory.deduct";
    public static final String NOTIFICATION_SEND_ROUTING_KEY = "notification.send";

    /**
     * 消息转换器 - 使用JSON格式
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter());
        
        // 设置消息确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息发送成功: " + correlationData);
            } else {
                System.err.println("消息发送失败: " + cause);
            }
        });
        
        // 设置消息返回回调
        rabbitTemplate.setReturnsCallback(returned -> {
            System.err.println("消息被退回: " + returned.getMessage() + 
                             ", Exchange: " + returned.getExchange() + 
                             ", RoutingKey: " + returned.getRoutingKey());
        });
        
        return rabbitTemplate;
    }

    /**
     * 监听器容器工厂配置
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(messageConverter());
        factory.setConcurrentConsumers(3);
        factory.setMaxConcurrentConsumers(10);
        return factory;
    }

    // ===============================
    // = 交换机Bean定义
    // ===============================
    
    @Bean
    public TopicExchange orderTopicExchange() {
        return new TopicExchange(ORDER_TOPIC_EXCHANGE);
    }
    
    @Bean
    public TopicExchange paymentTopicExchange() {
        return new TopicExchange(PAYMENT_TOPIC_EXCHANGE);
    }
    
    @Bean
    public TopicExchange marketingTopicExchange() {
        return new TopicExchange(MARKETING_TOPIC_EXCHANGE);
    }

    // ===============================
    // = 队列Bean定义
    // ===============================
    
    @Bean
    public Queue orderCreatedQueue() {
        return QueueBuilder.durable(ORDER_CREATED_QUEUE).build();
    }
    
    @Bean
    public Queue orderPaymentQueue() {
        return QueueBuilder.durable(ORDER_PAYMENT_QUEUE).build();
    }
    
    @Bean
    public Queue inventoryDeductionQueue() {
        return QueueBuilder.durable(INVENTORY_DEDUCTION_QUEUE).build();
    }
    
    @Bean
    public Queue notificationQueue() {
        return QueueBuilder.durable(NOTIFICATION_QUEUE).build();
    }

    // ===============================
    // = 绑定关系定义
    // ===============================
    
    @Bean
    public Binding orderCreatedBinding() {
        return BindingBuilder.bind(orderCreatedQueue())
                           .to(orderTopicExchange())
                           .with(ORDER_CREATED_ROUTING_KEY);
    }
    
    @Bean
    public Binding orderPaymentBinding() {
        return BindingBuilder.bind(orderPaymentQueue())
                           .to(orderTopicExchange())
                           .with(ORDER_PAID_ROUTING_KEY);
    }
    
    @Bean
    public Binding inventoryDeductionBinding() {
        return BindingBuilder.bind(inventoryDeductionQueue())
                           .to(orderTopicExchange())
                           .with(INVENTORY_DEDUCT_ROUTING_KEY);
    }
    
    @Bean
    public Binding notificationBinding() {
        return BindingBuilder.bind(notificationQueue())
                           .to(orderTopicExchange())
                           .with(NOTIFICATION_SEND_ROUTING_KEY);
    }
}